package entity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;
import util.Validator;

public class ParkReceipt {

	public String id;
	public String carId;
	public String parkId;
	public String entryIime;
	public String leaveIime;
	public Integer stockCount;
	public String money;
	public String createTime;
	
	public List<String[]> query(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select id, carId, parkId, entryIime,leaveIime,stockCount,money,createTime from pm_park_receipt where true ";
		if(Validator.isNotEmpty(params[0])){
			sql += " and carId like concat('%',?,'%')";
			list.add(params[0]);
		}
		sql += " order by id desc";
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 8);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}
	
	public boolean save() {
		String sql = "insert into pm_park_receipt(carId, parkId, entryIime,leaveIime,stockCount,money,createTime) "
				+ "values (?,?,?,?,?,?,?)";
		Object[] paraArray = {carId, parkId, entryIime,leaveIime,stockCount,money,createTime};
		try {
			int count = DBUtil.update(sql, paraArray);
			return count > 0;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public boolean load() {
		String sql = "select carId,parkId,entryIime,leaveIime,stockCount,money,createTime from pm_park_receipt where id = ?";
		Object[] paraArray = {id};
		try {
			String[] record = DBUtil.queryOne(sql, paraArray, 6);
			carId = record[0];
			parkId = record[1];
			entryIime = record[2];
			leaveIime = record[3];
			stockCount = Integer.valueOf(record[4]);
			money = record[5];
			createTime = record[6];
			return true;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public List<String[]> summarize(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select date_format(a.createTime,'%Y-%m-%d'),b.TYPE,ROUND(sum(replace(a.money,'元','') + 0),2)"
				+ " from pm_park_receipt a JOIN pm_park b ON a.parkId = b.id where TRUE ";		
		if(Validator.isNotEmpty(params[0])){
			sql += " and date_format(a.createTime,'%Y-%m-%d') >= ?";
			list.add(params[0]);
		}
		if(Validator.isNotEmpty(params[1])){
			sql += " and date_format(a.createTime,'%Y-%m-%d') <= ?";
			list.add(params[1]);
		}
		sql += " GROUP BY date_format(a.createTime,'%Y-%m-%d'),b.TYPE ORDER BY date_format(a.createTime,'%Y-%m-%d'),b.TYPE";
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 3);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}
	
}


